package main

import (
	pb "ihos/ihos"

	tm "github.com/golang/protobuf/ptypes/timestamp"
)

type yisheng struct {
	id   int32 //PK
	grxx int32 //个人信息 => basicinfo PK
	dlxx int32 //登录信息 => denglu PK
	jlsj int64 //建立时间，秒
	bm   string
	xm   string
	xb   int32
	tc   string
	js   string
	ks   string
}

func (w *yisheng) GetFromDB(id int32) error {
	sql := "SELECT id,grxx,dlxx,jlsj,bm,xm,xb,tc,js,ks FROM yisheng WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.grxx, &w.dlxx, &w.jlsj, &w.bm, &w.xm, &w.xb, &w.tc, &w.js, &w.ks)
}

func (w *yisheng) GetByDlxx(dlxx_id int32) error {
	sql := "SELECT id,grxx,dlxx,jlsj,bm,xm,xb,tc,js,ks FROM yisheng WHERE dlxx=$1"
	return DBConn.db.QueryRow(sql, dlxx_id).Scan(&w.id, &w.grxx, &w.dlxx, &w.jlsj, &w.bm, &w.xm, &w.xb, &w.tc, &w.js, &w.ks)
}

func (w *yisheng) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE yisheng set grxx=$1,dlxx=$2,jlsj=$3,bm=$4,xm=$5,xb=$6,tc=$7,js=$8,ks=$9 where id=$10 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.grxx, w.dlxx, w.jlsj, w.bm, w.xm, w.xb, w.tc, w.js, w.ks, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO yisheng(grxx,dlxx,jlsj,bm,xm,xb,tc,js,ks) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.grxx, w.dlxx, w.jlsj, w.bm, w.xm, w.xb, w.tc, w.js, w.ks).Scan(&w.id)
	}
	return err
}

func (w *yisheng) toPB() *pb.YiShengInfoL3 {
	y := &pb.YiShengInfoL3{
		ID:   w.id,
		GRXX: &pb.BasicInfoL1{ID: w.grxx},
		// LXFS  : &pb.ContactInfoL1{},
		DLXX: &pb.DengLuL2{},
		// DLSJ  :
		YS: &pb.YiSheng{
			ID: w.id,
			BM: w.bm,
			XM: w.xm,
			XB: pb.GENDER(w.xb),
			TC: w.tc,
			JS: w.js,
			KS: &pb.KeShi{BM: w.ks},
		},
		JLSJ: &tm.Timestamp{Seconds: w.jlsj},
		// DQSPFJ:
	}
	b := &basicinfo{}
	if err := b.GetFromDB(w.grxx); err != nil {
		return nil
	} else {
		y.GRXX = b.toPB()
	}
	d := &denglu{}
	if err := d.GetFromDB(w.dlxx); err != nil {
		return nil
	} else {
		y.DLXX = d.toPB()
	}
	return y
}

func (w *yisheng) fromPB(p *pb.YiShengInfoL3) *yisheng {
	w.id = p.GetID()
	w.grxx = p.GetGRXX().GetID()
	w.dlxx = p.GetDLXX().GetJS().GetID()
	w.jlsj = p.GetJLSJ().GetSeconds()
	w.bm = p.GetYS().GetBM()
	w.xm = p.GetYS().GetXM()
	w.xb = int32(p.GetYS().GetXB())
	w.tc = p.GetYS().GetTC()
	w.js = p.GetYS().GetJS()
	w.ks = p.GetYS().GetKS().GetBM()
	return w
}
